#include "stdafx.h"
#include <Strsafe.h>
#include <Shlwapi.h>
#include <wchar.h>
#include "Registry.h"
#include "HttpFx.h"

#pragma comment(lib,"Shlwapi.lib")
HttpFx::HttpFx(PTSTR sn,ushort ver):Http(agent(sn,ver)){
	checksum=0;
	version=0;
};

PTSTR HttpFx::agent(PTSTR sn,ushort ver){
	uint m=ver >> 8;
	uint n=ver & 0xff;
	StringCbPrintf(buffer,sizeof(buffer),
		_T("XYNC/0.5 (Windows NT 5.1) SerialNumber=%s, Firmware=%d.%d"),sn,m,n);
	return buffer;
}
Bin* HttpFx::get(PTSTR location,PTSTR sn,ushort ver){
	HINTERNET req=WinHttpOpenRequest(connect,L"GET",location,NULL,
		WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,0);
	if(!req)
		throw(0);
	if(sn){
		TCHAR x[1024];
		StringCbPrintf(x,sizeof(x),_T("Serial-Number: %s.%d"),sn,ver);
		WinHttpAddRequestHeaders(req,x,-1L,WINHTTP_ADDREQ_FLAG_ADD);
	}
	Bin* ret=Http::get(req);
	WinHttpCloseHandle(req);
	return ret;
}
String* HttpFx::hostName(void){
	try{
		MachineOrUser reg(L"Software\\Phoxell\\xync");
		return reg.get(L"host",L"www.phoxell.com");
	}catch(int){
		return new String(L"www.phoxell.com");
	}
}
void HttpFx::onCallback(HINTERNET inernet,uint status,LPVOID info,uint length){
	if(status==WINHTTP_CALLBACK_STATUS_REDIRECT){
		uint len=0;
		WinHttpQueryHeaders(inernet,WINHTTP_QUERY_RAW_HEADERS_CRLF,
			WINHTTP_HEADER_NAME_BY_INDEX,NULL,&len,WINHTTP_NO_HEADER_INDEX);
		if(len){
			if(TCHAR* buf=(TCHAR*)malloc(len)){
				WinHttpQueryHeaders(inernet,WINHTTP_QUERY_RAW_HEADERS_CRLF,
					WINHTTP_HEADER_NAME_BY_INDEX,buf,&len,
					WINHTTP_NO_HEADER_INDEX);
				TCHAR *s=StrStrI(buf,L"Checksum:");
				TCHAR *v=StrStrI(buf,L"Version:");
				if(s){
					s+=10;
					TCHAR *p=StrChr(s,L'\n');
					if(p)
						*p=0;
					swscanf_s(s,L"%d",&checksum);
				}
				if(v){
					v+=9;
					TCHAR *p=StrChr(v,L'\n');
					if(p)
						*p=0;
					swscanf_s(v,L"%d",&version);
				}
				free(buf);
			}
		}
	}
}